package com.laikan.reader.core.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.*;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.ChapterBean;
import com.laikan.reader.core.bean.ChapterDetailBean;
import com.laikan.reader.core.utils.EncryptUtils;
import com.laikan.reader.core.utils.FileUtil;
import com.socks.library.KLog;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class LoadService extends Service {

    private File File = null;
    private Intent intent = new Intent("com.example.communication.RECEIVER");
    @SuppressWarnings ("unused")
    private int progress;
    private boolean flag = false;
    private int Sum = 0;
    private MyBinder myBinder = new MyBinder();
    private File Filejson;
    private Handler handler = new Handler();
    private ExecutorService executorService = Executors.newFixedThreadPool(3);
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @SuppressWarnings ("unchecked")
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("com.laikan.service.load")) {
                loadAll((ArrayList<ChapterBean>)intent.getSerializableExtra("mData"), intent.getStringExtra("book_id"));
            }
        }

    };

    @Override
    public IBinder onBind(Intent intent) {
        return myBinder;
    }

    public void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction("com.laikan.service.load");
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    public void MyMethod(ArrayList<ChapterBean> mData, String book_id) {
        loadAll(mData, book_id);
    }

    // 获取已下载章节id
    public List<String> getFile(File file) {
        List<String> mFileList = new ArrayList<String>();
        File[] fileArray = file.listFiles();
        try {
            for (File f : fileArray) {
                if (f.isFile()) {
                    mFileList.add(f.getName());
                }else {
                    getFile(f);
                }
            }
        }catch (Exception e) {
            // TODO: handle exception
        }

        return mFileList;
    }

    private void loadAll(final ArrayList<ChapterBean> mData, final String book_id) {
        Sum = mData.size();
        List<String> mFileList = new ArrayList<String>();
        if (FileUtil.isHaveSDCard()) {
            Filejson = Environment.getExternalStorageDirectory();
            File f = new File(Filejson.getPath() + "/LaikanReader/book/" + book_id);
            mFileList = getFile(f);
        }else {
            Filejson = Environment.getDataDirectory();
        }
        for (int i = 0; i < mData.size(); i++) {
            // TODO 判断是否已下载
            if (mFileList.contains(mData.get(i).getId())) {
                continue;
            }
            if (flag) {
                ToastMgr.showShortToast("下载完成");
                SPUtil.putBoolean("down_char", false);
                break;
            }
            if (!mData.get(i).isVolume()) {
                if (FileUtil.isHaveSDCard()) {
                    File = Environment.getExternalStorageDirectory();
                }else {
                    File = Environment.getDataDirectory();
                }
                @SuppressWarnings ("unused")
                final int pos = i;
                loadImage3(mData, i, book_id);
            }
        }
    }

    // 引入线程池来管理多线程
    private void loadImage3(final ArrayList<ChapterBean> mData, final int i, final String book_id) {
        executorService.submit(new Runnable() {
            public void run() {
                try {
                    // 模拟网络延时
                    SystemClock.sleep(2000);
                    handler.post(new Runnable() {
                        public void run() {
                            HashMap<String, String> map = new HashMap<String, String>();
                            map.put("sd", SPUtil.getString("token", ""));
                            RequestListener requestListener = new RequestListener() {
                                @Override
                                public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

                                @Override
                                public void onSuccess(HttpResponse httpResponse) {
                                    BaseDataBean<ChapterDetailBean> result;
                                    Gson gson = new Gson();
                                    Type type = new TypeToken<BaseDataBean<ChapterDetailBean>>() {}.getType();
                                    try {
                                        result = gson.fromJson(httpResponse.responseContent, type);
                                        if (result.getResult().equals(

                                            "1")) {
                                            if (!result.getError_no().equals("600")) {
                                                saveFile(mData.get(i).getId(), httpResponse.responseContent, book_id);
                                            }else {
                                                flag = true;
                                                SPUtil.putBoolean("down_char", false);
                                                return;
                                            }

                                        }else {
                                            flag = true;
                                            SPUtil.putBoolean("down_char", false);
                                            return;
                                        }
                                    }catch (JsonSyntaxException e) {
                                        // 数据解析失败
                                        e.printStackTrace();
                                        SPUtil.putBoolean("down_char", false);
                                        return;
                                    }
                                }

                                @Override
                                public void onError(VolleyErrorHandler errorHandler) {

                                }

                                @Override
                                public void onFinish() {

                                }
                            };

                            Requester requester = new Requester();
                            requester.setUrl(APIProtocol.getRootURL() + "/book/" + book_id + "_" + mData.get(i).getId() + "?");
                            requester.setMapBody(map);
                            HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

                           /* HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.getRootURL() + "/book/" + book_id + "_" + mData.get(i).getId() + "?", map, null, null,
                                requestListener);*/
                        }
                    });
                }catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    private void saveFile(final String chapterid, String json, String book_id) {
        if (FileUtil.isHaveSDCard()) {
            File = Environment.getExternalStorageDirectory();
        }else {
            File = Environment.getDataDirectory();
        }
        File = new File(File.getPath() + "/LaikanReader/book/" + book_id + "/" + chapterid);
        if (!File.isDirectory()) {
            File.delete();
            File.mkdirs();
        }
        if (!File.exists()) {
            File.mkdirs();
        }
        // 内容加密
        // FileUtil.writeFileDes(File.getPath(), json);

        // 文件加密
        String sKey = "123456789012345678901234567890123456789088888888";
        EncryptUtils.encrypt(new File(File.getPath()), sKey, json);

        // TODO 章节存在数据统计

        if (FileUtil.isHaveSDCard()) {
            File = Environment.getExternalStorageDirectory();
        }else {
            File = Environment.getDataDirectory();
        }
        String path = File.getPath() + "/LaikanReader/book/" + book_id;
        int fileCount = 0;
        @SuppressWarnings ("unused")
        int folderCount = 0;
        File d = new File(path);
        File list[] = d.listFiles();
        for (int i = 0; i < list.length; i++) {
            if (list[i].isFile()) {
                fileCount++;
            }else {
                folderCount++;
            }
        }
        // ToastMgr.showShortToast( "文件个数：" + fileCount
        // + "-------" + "文件夹数：" + folderCount);
        // progress = fileCount + 1;
        // if (flag) {
        // ToastMgr.showShortToast( "下载完成");
        // flag = false;
        // }
        intent.putExtra("progress", fileCount - 1);
        sendBroadcast(intent);
    }

    public class MyBinder extends Binder {

        public LoadService getService() {
            return LoadService.this;
        }
    }

}
